export default {
	name: "fileoperation",
	props: {
		modelValue: Boolean,
		type: String, // rename/move/copy/zip/unzip
		file: [Object, Array],
        currentPath: {
            type: String,
            default: '', // 确保默认值为空字符串
            validator: (value) => {
                // 路径格式校验
                return !/[\\:*?"<>|]/.test(value)
            }
        },
	},
	emits: ['update:modelValue', 'confirm'],
	setup(props, {emit}) {
        const operationTitles = {
		    share: '分享文件',
			rename: '重命名',
			move: '移动文件',
			copy: '复制文件',
			zip: '压缩文件',
			unzip: '解压文件'
		}
		const form = ref({})
		const formRef = ref()
		const dirTree = ref([]);
    	const treeProps = {
    		label: 'name',
    		children: 'children',
    		isLeaf: 'isLeaf'
    	};
        const pathRules = (_, value, callback) => {
            if (!value) return callback(new Error('请选择目标路径'));
            // 标准化目标路径
            const normalizedValue = value.endsWith('/') ? value.slice(0, -1) : value;
            // 获取原文件所在目录并标准化
            const sourcePath = props.file?.fullPath || '';
            let sourceDir = '';
            if (sourcePath) {
                // 提取目录路径：如果原路径是文件，则获取其所在目录
                const lastSlashIndex = sourcePath.lastIndexOf('/');
                sourceDir = lastSlashIndex === -1 ? '' : sourcePath.substring(0, lastSlashIndex);
            }
            const normalizedSource = sourceDir.endsWith('/') ? sourceDir.slice(0, -1) : sourceDir;
            // 检查是否与原目录相同
            if (normalizedValue === normalizedSource) {
                return callback(new Error('不能选择原路径'));
            }
            // 检查是否是原目录的子目录
            if (normalizedSource && normalizedValue.startsWith(normalizedSource + '/')) {
                return callback(new Error('不能选择子目录'));
            }
            callback();
        };
        const dirRules = [
            { required: true, message: '请选择目标目录' },
            { validator: pathRules }
        ];
        
        const nameRules = [
            { pattern: /^[^\\/:*?"<>|]+$/, message: '包含非法字符' }
        ];
		
		// 动态加载目录节点
        const loadDirNodes = async (node, resolve) => {
            try {
                // 获取当前节点的安全路径（根节点特殊处理）
                const parentPath = node.level === 0 ? '' : node.data?.safePath || '';
                const res = await dirfilelist({ path: parentPath });
                // 生成子节点路径时保留完整层级
                const nodes = res.items.filter(item => {
                        // 强化校验（与后端规则一致）
                        return item.name &&
                               !item.name.startsWith('.') &&
                               !item.name.includes('..') &&
                               (parentPath === '' || item.path.startsWith(`${parentPath}/`)) // 关键路径连续性检查
                    }).map(item => ({
                        name: item.name,
                        safePath: item.path, // 直接使用后端返回的完整相对路径
                        isLeaf: !item.hasChild
                    }));
                resolve(nodes);
            } catch (error) {
                console.error('加载目录失败:', error);
                resolve([]);
            }
        };
	
		// 处理路径选择
        const handlePathSelect = (data) => {
            // 添加空值保护
            const selectedPath = data?.safePath || '';
            form.value.targetDir = selectedPath;
            // 仅在未修改时自动填充文件名
            if (!form.value.targetName?.trim() && props.file?.name) {
                form.value.targetName = props.file.name.replace(/\.[^.]+$/, ''); // 去除扩展名
            }
        }
		
        // 获取完整路径的计算属性
        const fullTargetPath = computed(() => {
            const dir = form.value.targetDir || ''
            const fileName = form.value.targetName || ''
            // 处理空路径情况
            if (!dir) return fileName
            // 标准化目录分隔符
            const normalizedDir = dir.endsWith('/') ? dir : `${dir}/`
            return normalizedDir + fileName
        })

		// 根据操作类型初始化表单
		const initForm = () => {
            const basePath = props.currentPath || ''
            const baseDir = basePath.endsWith('/') ? basePath : `${basePath}/`
		    if (props.type === 'share') {
				form.value = {
					path: props.file?.fullPath || '',
					expirehours: 24, //过期时间(小时)
					password:'',
				}
			}
			if (props.type === 'rename') {
			    console.log(props.file)
                form.value = {
                    oldPath: props.file?.fullPath || '',
                    newName: props.file?.name || ''
                }
			}
            if (['move', 'copy'].includes(props.type)) {
                form.value = {
                    source: props.file?.fullPath || '',
                    targetDir: baseDir,
                    targetName: props.file?.name || '',
                    overwrite: false
                }
            }
			if (['zip', 'unzip'].includes(props.type)) {
				form.value = {
					zipName: props.file?.name || 'archive.zip',
					zipPath: baseDir,
				}
				console.log(form.value)
			}
		}

		const handleConfirm = async () => {
			await formRef.value.validate();
            emit('confirm', {
                ...form.value,
                target: fullTargetPath.value // 发送完整路径
            });
			emit('update:modelValue', false);
		};

		const handleCancel = () => {
			emit('update:modelValue', false);
		};

		const operationTitle = computed(() => operationTitles[props.type] || '文件操作');

		watch(
			() => props.modelValue,
			(newVal) => {
			    console.log('Dialog visible:', newVal);
				if (newVal) initForm();
			}
		);

		return {
			operationTitles,
			form,
			formRef,
			initForm,
			handleConfirm,
			operationTitle,
			handleCancel,
			dirTree,
			treeProps,
			loadDirNodes,
			handlePathSelect,
            dirRules,
            nameRules,
			fullTargetPath,
			pathRules
		};
	},
        
    template: `
	<el-dialog :model-value="modelValue"  :title="operationTitle" width="500px" destroy-on-close>
		<!-- 动态表单 -->
		<el-form ref="formRef" :model="form" label-width="80px">
			<!-- 分享 -->
			<template v-if="type === 'share'">
				<el-form-item label="文件名" prop="path" :rules="[{ required: true, message: '请选择文件' }]">
					<el-input v-model="form.path" disabled/>
				</el-form-item>
				<el-form-item label="过期时间" prop="expirehours" :rules="[{ required: true, message: '设置过期时间' }]">
					<el-input-number v-model="form.expirehours" :min="0" :max="10000" :step="1" style="margin-right:5px;"/> 小时
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="form.password" placeholder="是否要密码访问文件"/>
				</el-form-item>
			</template>
		
			<!-- 重命名 -->
			<template v-if="type === 'rename'">
                <el-form-item label="新名称" prop="newName" :rules="[{ required: true, message: '请输入新名称' }]">
                    <el-input v-model="form.newName" />
                </el-form-item>
                <el-form-item label="原路径" prop="oldPath" :rules="[{ required: true, message: '请选择文件' }]">
                    <el-input v-model="form.oldPath" disabled />
                </el-form-item>
			</template>

			<!-- 移动/复制 -->
			<template v-if="['move', 'copy'].includes(type)">
				<el-form-item label="目标目录" prop="targetDir" :rules="dirRules">
					<el-popover placement="bottom-start" :width="400" trigger="click" popper-class="path-select-popover">
						<template #reference>
							<el-input v-model="form.targetDir" placeholder="点击选择或输入路径" clearable class="path-select-input">
								<template #prefix>
									<el-icon>
										<FolderOpened />
									</el-icon>
								</template>
							</el-input>
						</template>
						<!-- 树形路径选择器 -->
						<div class="inline-path-picker">
							<el-tree :data="dirTree" :props="treeProps" :load="loadDirNodes" lazy node-key="path"
								highlight-current @node-click="handlePathSelect">
								<template #default="{ node, data }">
									<div class="tree-node-item">
										<el-icon>
											<Folder />
										</el-icon>
										<span class="node-label">{{ node.label }}</span>
										<span v-if="data.loading" class="loading-icon">
											<el-icon class="is-loading">
												<Loading />
											</el-icon>
										</span>
									</div>
								</template>
							</el-tree>
						</div>
					</el-popover>
				</el-form-item>
                <el-form-item label="文件名称" prop="targetName" :rules="nameRules">
                    <el-input 
                        v-model="form.targetName"
                        placeholder="输入新文件名（可选）"/>
                </el-form-item>
            
                <el-form-item label="完整路径" class="path-preview">
                    <el-tag type="info">{{ fullTargetPath }}</el-tag>
                </el-form-item>
			</template>

			<!-- 压缩 -->
			<template v-if="type === 'zip'">
				<el-form-item label="压缩名称" prop="zipName" :rules="[{ required: true, message: '请输入压缩包名称' }]">
					<el-input v-model="form.zipName" placeholder="example.zip" />
				</el-form-item>
			</template>
			
			<!-- 解压 -->
			<template v-if="type === 'unzip'">
				<el-form-item label="压缩名称" prop="zipName" :rules="[{ required: true, message: '请输入压缩包名称' }]">
					<el-input v-model="form.zipName" placeholder="example.zip" disabled/>
				</el-form-item>
			</template>
		</el-form>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleConfirm">确定</el-button>
		</template>
	</el-dialog>
    `
}